<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      class PublishSubscribeCenter {
        // 事件频道
        eventChannel = {};

        // 订阅
        subscribe(type, callback) {
          //向事件频道中添加不同类型的事件（同一时间可以订阅多个方法）
          if (this.eventChannel[type]) {
            this.eventChannel[type].push(callback);
          } else {
            this.eventChannel[type] = [callback];
          }
        }

        // 取消订阅
        unsubscribe(type, callback) {
          if (this.eventChannel[type]) {
            if (callback) {
              this.eventChannel[type] = this.eventChannel[type].filter(
                (func) => func !== callback
              );
            } else {
              this.eventChannel[type] = [];
            }
          }
        }

        // 发布事件
        publish(type, data) {
          if (this.eventChannel[type]) {
            const events = this.eventChannel[type];
            events.forEach((callback) => {
              callback(data);
            });
          }
        }
      }

      const pbc = new PublishSubscribeCenter();

      const funcA = function (data) {
        console.log("方法A调用了：", data);
      };

      const funcB = function (data) {
        console.log("方法B调用了：", data);
      };

      const funcC = function (data) {
        console.log("方法C调用了：", data);
      };

      const funcD = function (data) {
        console.log("方法D调用了：", data);
      };

      pbc.subscribe("A", funcA);
      pbc.subscribe("A", funcB);
      pbc.subscribe("A", funcC);
      pbc.subscribe("B", funcB);
      pbc.subscribe("B", funcC);
      pbc.subscribe("C", funcA);
    </script>
  </body>
</html>
